package com.cpp.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cpp.common.enums.CourseStatus;
import com.cpp.common.enums.UserRoleEnum;
import com.cpp.common.exception.BaseException;
import com.cpp.common.properties.PageProperties;
import com.cpp.common.result.PageResult;
import com.cpp.pojo.dto.course.CourseCreateDTO;
import com.cpp.pojo.dto.course.CoursePageDTO;
import com.cpp.pojo.dto.course.CourseUpdateDTO;
import com.cpp.pojo.pojo.Course;
import com.cpp.pojo.pojo.StudentCourse;
import com.cpp.pojo.pojo.User;
import com.cpp.pojo.vo.course.CourseVO;
import com.cpp.pojo.vo.course.StudentCourseVO;
import com.cpp.server.aspect.annotation.UserRole;
import com.cpp.server.context.UserHolder;
import com.cpp.server.mapper.CourseMapper;
import com.cpp.server.mapper.StudentCourseMapper;
import com.cpp.server.mapper.UserMapper;
import com.cpp.server.service.CourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 34044
 * @description 针对表【course】的数据库操作Service实现
 * @createDate 2025-05-14 13:13:49
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    private final StudentCourseMapper studentCourseMapper;
    private final PageProperties pageProperties;
    private final CourseMapper courseMapper;
    private final UserMapper userMapper;

    @Override
    @UserRole(roles = { UserRoleEnum.STUDENT})
    public void saveSelectCourse(List<Long> ids) {

        //判断数据准备
        User currentUser = UserHolder.getCurrentUser();
        //查询已选课程
        LambdaQueryWrapper<StudentCourse> studentCourseWrapper = new LambdaQueryWrapper<>();
        studentCourseWrapper.eq(StudentCourse::getStudentId, currentUser.getId());
        List<StudentCourse> studentCourse = studentCourseMapper.selectList(studentCourseWrapper);
        if (ids == null || ids.isEmpty()) {
            throw new BaseException("请选择课程");
        }

        //判断是否有已选
        for (StudentCourse course : studentCourse) {
            if (ids.stream().anyMatch(id -> id.equals(course.getCourseId()))) {
                throw new BaseException("你已经选过" + course.getName() + "课程了");
            }
        }
        //业务数据准备
        Long studentId = UserHolder.getCurrentUser().getId();
        List<StudentCourse> studentCourses = new ArrayList<>();

        //条件查询准备
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Course::getId, ids);

        //查询
        List<Course> courses = list(queryWrapper);
        for (Course course : courses) {
            StudentCourse studentCourseResult = StudentCourse.builder()
                    .studentId(studentId)
                    .name(course.getName())
                    .description(course.getDescription())
                    .courseId(course.getId())
                    .build();
            studentCourses.add(studentCourseResult);
        }


        studentCourseMapper.insert(studentCourses);
    }

//    | 功能/方法                          | pageCourseForAdmin                         | pageCourseForTeacher                       | pageCourseForStudent                                  |
//            |-----------------------------------|--------------------------------------------|--------------------------------------------|-------------------------------------------------------|
//            | **查询范围**                      | 所有课程                                   | 当前教师自己的课程                         | 所有未被选过的课程（过滤掉学生已选课程）             |
//            | **教师姓名来源**                  | 从 User 表中查出所有创建者信息             | 直接使用当前教师的真实姓名                 | 从 User 表中查出所有创建者信息                        |
//            | **是否过滤已选课**                | 否                                         | 否                                         | 是，过滤掉学生已选课程                                |
//            | **VO 构建方式**                   | 与 users 匹配构建                          | 全部设置为当前教师姓名                     | 与 users 匹配构建                                     |
//            | **
//    SQL 查询次数**                  | 2 次（courses + users）                    | 1 次（仅 courses）                         | 3 次（courses + studentCourses + users）              |

    //查询课程
    @Override
    public PageResult pageCourse(CoursePageDTO coursePageDTO) {
        //判断数据准备
        User currentUser = UserHolder.getCurrentUser();
        Integer page = coursePageDTO.getPageNum();
        Integer pageSize = coursePageDTO.getPageSize();

        if (page == null || page <= 0) {
            coursePageDTO.setPageNum(pageProperties.getPage());
        }
        if (pageSize == null || pageSize <= 0) {
            coursePageDTO.setPageSize(pageProperties.getPageSize());
        }
        if (currentUser.getRole().equals(UserRoleEnum.STUDENT.getRole())) {
            return pageCourseForStudent(coursePageDTO, currentUser);
        } else if (currentUser.getRole().equals(UserRoleEnum.TEACHER.getRole())) {
            return pageCourseForTeacher(coursePageDTO, currentUser);
        } else if (currentUser.getRole().equals(UserRoleEnum.ADMIN.getRole())) {
            return pageCourseForAdmin(coursePageDTO);
        }
        throw new BaseException("当前用户权限异常");
    }

    private PageResult pageCourseForAdmin(CoursePageDTO coursePageDTO) {
        //查询课程信息
        String courseName = coursePageDTO.getName();
        Page<Course> pageQuery = new Page<>(coursePageDTO.getPageNum(), coursePageDTO.getPageSize());
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(courseName != null && !courseName.isEmpty(), Course::getName, courseName);
        queryWrapper.eq(Course::getStatus, CourseStatus.NOT_DELETED.getCode());

        Page<Course> coursePage = courseMapper.selectPage(pageQuery, queryWrapper);
        List<Course> courses = coursePage.getRecords();

        //查询课程创建者姓名
        List<Long> UserIds = courses.stream().map(Course::getUserId).toList();
        if (UserIds.isEmpty()){
            return new PageResult(0,new ArrayList<>());
        }
        List<User> users = userMapper.selectBatchIds(UserIds);
        List<CourseVO> courseVOS = new ArrayList<>();
        for (Course course : courses) {
            for (User user : users) {
                if (user.getId().equals(course.getUserId())) {
                    CourseVO courseVO = CourseVO.builder()
                            .courseId(course.getId())
                            .name(course.getName())
                            .description(course.getDescription())
                            .teacherName(user.getRealName())
                            .build();
                    courseVOS.add(courseVO);
                }
            }
        }
        // 封装为自定义的 PageResult 返回
        return new PageResult(coursePage.getTotal(), courseVOS);
    }

    private PageResult pageCourseForTeacher(CoursePageDTO coursePageDTO, User currentUser) {
        User user =UserHolder.getCurrentUser();
        //查询条件准备
        String courseName = coursePageDTO.getName();
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(courseName != null && !courseName.isEmpty(), Course::getName, courseName);
        queryWrapper.eq(Course::getUserId, currentUser.getId());
        queryWrapper.eq(Course::getStatus, CourseStatus.NOT_DELETED.getCode());

        // 使用 MyBatis Plus 分页：当前页码、每页条数
        Page<Course> pageQuery = new Page<>(coursePageDTO.getPageNum(), coursePageDTO.getPageSize());

        // 执行分页查询
        Page<Course> coursePage = courseMapper.selectPage(pageQuery, queryWrapper);
        List<Course> courses = coursePage.getRecords();
        List<CourseVO> courseVOS = new ArrayList<>();

        for (Course cours : courses) {
            CourseVO courseVO = CourseVO.builder()
                    .courseId(cours.getId())
                    .name(cours.getName())
                    .description(cours.getDescription())
                    .teacherName(user.getRealName())
                    .build();
            courseVOS.add(courseVO);

        }

        for (CourseVO courseVO : courseVOS) {
            courseVO.setTeacherName(currentUser.getRealName());
        }
        // 封装为自定义的 PageResult 返回
        return new PageResult(coursePage.getTotal(), courseVOS);
    }

    private PageResult pageCourseForStudent(CoursePageDTO coursePageDTO, User currentUser) {
        //查询条件准备
        String courseName = coursePageDTO.getName();
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Course::getStatus, CourseStatus.NOT_DELETED.getCode());
        queryWrapper.like(courseName != null && !courseName.isEmpty(), Course::getName, courseName);
        Integer page = coursePageDTO.getPageNum();
        Integer pageSize = coursePageDTO.getPageSize();
        if (page == null || page <= 0) {
            coursePageDTO.setPageNum(pageProperties.getPage());
        }
        if (pageSize == null || pageSize <= 0) {
            coursePageDTO.setPageSize(pageProperties.getPageSize());
        }
        // 使用 MyBatis Plus 分页：当前页码、每页条数
        Page<Course> pageQuery = new Page<>(page, pageSize);

        // 执行分页查询
        Page<Course> coursePage = courseMapper.selectPage(pageQuery, queryWrapper);

        //数据处理
        List<Course> courses = coursePage.getRecords();

        //去除已选课程
        LambdaQueryWrapper<StudentCourse> studentCourseWrapper = new LambdaQueryWrapper<>();
        studentCourseWrapper.eq(StudentCourse::getStudentId, currentUser.getId());
        List<StudentCourse> studentCourses = studentCourseMapper.selectList(studentCourseWrapper);
        for (StudentCourse studentCourse : studentCourses) {
            courses.removeIf(course -> course.getId().equals(studentCourse.getCourseId()));
        }
        //封装数据
        List<Long> UserIds = courses.stream().map(Course::getUserId).toList();
        if (UserIds.isEmpty()){
            return new PageResult(0,new ArrayList<>());
        }
        List<User> users = userMapper.selectBatchIds(UserIds);
        List<CourseVO> courseVOS = new ArrayList<>();
        //courses和users里的用户userid相同的话，把realName赋给courseVO

        for (Course course : courses) {
            for (User user : users) {
                if (user.getId().equals(course.getUserId())) {
                    CourseVO courseVO = CourseVO.builder()
                            .courseId(course.getId())
                            .name(course.getName())
                            .description(course.getDescription())
                            .teacherName(user.getRealName())
                            .build();
                    courseVOS.add(courseVO);
                }
            }
        }

        // 封装为自定义的 PageResult 返回
        return new PageResult(coursePage.getTotal(), courseVOS);
    }

    // 分页查询学生已选择选课列表
    @Override
    @UserRole(roles = { UserRoleEnum.STUDENT})
    public PageResult pageSelectedCourse(CoursePageDTO coursePageDTO) {
        //判断数据准备
        User currentUser = UserHolder.getCurrentUser();
        if (!currentUser.getRole().equals(UserRoleEnum.STUDENT.getRole())) {
            throw new BaseException("只有学生才能已选择选课列表");
        }
        //分页数据准备
        Integer page = coursePageDTO.getPageNum();
        Integer pageSize = coursePageDTO.getPageSize();
        if (page == null || page <= 0) {
            page = pageProperties.getPage();
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = pageProperties.getPageSize();
        }
        Page<StudentCourse> pageQuery = new Page<>(page, pageSize);

        //查询条件准备
        LambdaQueryWrapper<StudentCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentCourse::getStudentId, currentUser.getId());

        //执行分页查询
        Page<StudentCourse> studentCoursePage = studentCourseMapper.selectPage(pageQuery, queryWrapper);

        //数据处理
        List<StudentCourse> courses = studentCoursePage.getRecords();

        List<StudentCourseVO> studentCourseVOS = new ArrayList<>();
        for (StudentCourse cours : courses) {
            StudentCourseVO studentCourseVO = StudentCourseVO.builder()
                    .studentCourseId(cours.getId())
                    .name(cours.getName())
                    .description(cours.getDescription())
                    .build();
            studentCourseVOS.add(studentCourseVO);
        }

        return new PageResult(studentCoursePage.getTotal(), studentCourseVOS);
    }

    @Override
    @UserRole(roles = { UserRoleEnum.STUDENT})
    public void deleteSelectCourse(List<Long> ids) {
        //判断数据准备
        User currentUser = UserHolder.getCurrentUser();
        if (ids == null || ids.isEmpty()) {
            throw new BaseException("请选择要删除的课程哦");
        }
        List<StudentCourse> courses = studentCourseMapper.selectBatchIds(ids);
        for (StudentCourse course : courses) {
            if (!course.getStudentId().equals(currentUser.getId())) {
                throw new BaseException("只能删除自己的选课哦");
            }
        }
        studentCourseMapper.deleteByIds(ids);
    }

    @Override
    @UserRole(roles = { UserRoleEnum.TEACHER})
    public void saveCourse(CourseCreateDTO courseVO) {
        User currentUser = UserHolder.getCurrentUser();
        Course course = Course.builder()
                .subjectId(courseVO.getSubjectId())
                .name(courseVO.getName())
                .description(courseVO.getDescription())
                .userId(currentUser.getId())
                .build();
        courseMapper.insert(course);

    }

    @Override
    @UserRole(roles = { UserRoleEnum.TEACHER})
    public void updateCourse(CourseUpdateDTO courseVO) {
        User currentUser = UserHolder.getCurrentUser();
        Course course = courseMapper.selectById(courseVO.getCourseId());

        if (course.getUserId()!=currentUser.getId()){
            throw new BaseException("只能修改自己的课程哦");
        }
        course.setName(courseVO.getName());
        course.setDescription(courseVO.getDescription());
        course.setSubjectId(courseVO.getSubjectId());

        courseMapper.updateById(course);
    }

    @Override
    @UserRole(roles = { UserRoleEnum.TEACHER})
    public void removeCourse(List<Long> ids) {
        User currentUser = UserHolder.getCurrentUser();
        List<Course> courses = courseMapper.selectBatchIds(ids);
        for (Course cours : courses) {
            if (!cours.getUserId().equals(currentUser.getId())){
                throw new BaseException("只能删除自己的课程哦");
            }
            cours.setStatus(CourseStatus.DELETED.getCode());
        }
        courseMapper.updateById(courses);
    }
}




